<!--
 * @Author: Abdusalam0126 2383624944@qq.com
 * @Date: 2025-08-05 16:29:08
 * @LastEditors: Abdusalam0126 2383624944@qq.com
 * @LastEditTime: 2025-08-05 17:30:56
 * @FilePath: src/pages/profile/edit.vue
 * @Description: 这是默认设置,可以在设置》工具》File Description中进行配置
 -->
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { userApi } from '@/utils/api'
import { useI18n } from '@/composables/useI18n'
import { usePageTitle } from '@/composables/usePageTitle'

const userStore = useUserStore()
const { t } = useI18n()
const loading = ref(false)

// 设置页面标题
usePageTitle('pages/profile/edit')

// 表单数据
const formData = reactive({
  nickname: '',
  email: '',
  phone: '',
  avatar_url: ''
})






// 获取用户资料
const fetchUserProfile = async () => {
  if (!userStore.userId) {
    uni.showToast({
      title: t('profile.editPage.save.invalidUserId'),
      icon: 'none'
    })
    return
  }

  try {
    const data = await userApi.getUserProfile(userStore.userId)
    console.log('用户资料数据:', data)

    // 填充表单数据
    Object.assign(formData, {
      nickname: data.nickname || '',
      email: data.email || '',
      phone: data.phone || '',
      avatar_url: data.avatar_url || ''
    })
  } catch (err: any) {
    console.error('获取用户资料失败:', err)
    uni.showToast({
      title: t('error.dataLoadFailed'),
      icon: 'none'
    })
  }
}

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0]
      uploadAvatar(tempFilePath)
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
      uni.showToast({
        title: t('profile.editPage.avatar.selectFailed'),
        icon: 'none'
      })
    }
  })
}

// 上传头像
const uploadAvatar = async (filePath: string) => {
  if (!userStore.userId) {
    uni.showToast({
      title: t('profile.editPage.save.invalidUserId'),
      icon: 'none'
    })
    return
  }

  try {
    const data = await userApi.uploadAvatar(userStore.userId, filePath)
    formData.avatar_url = data.avatar_url
    uni.showToast({
      title: t('profile.editPage.avatar.uploadSuccess'),
      icon: 'success'
    })
  } catch (err: any) {
    console.error('头像上传失败:', err)
    uni.showToast({
      title: t('profile.editPage.avatar.uploadFailed'),
      icon: 'none'
    })
  }
}

// 保存资料
const saveProfile = async () => {
  if (!userStore.userId) {
    uni.showToast({
      title: t('profile.editPage.save.invalidUserId'),
      icon: 'none'
    })
    return
  }

  loading.value = true

  try {
    // 过滤空值
    const updateData = Object.fromEntries(
      Object.entries(formData).filter(([_, value]) => value !== '')
    )

    await userApi.updateUserProfile(userStore.userId, updateData)

    uni.showToast({
      title: t('profile.editPage.save.success'),
      icon: 'success'
    })

    // 返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)

  } catch (err: any) {
    console.error('保存资料失败:', err)
    uni.showToast({
      title: t('profile.editPage.save.failed'),
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 页面加载时获取用户资料
onMounted(() => {
  fetchUserProfile()
})
</script>

<template>
  <view class="container">


    <view class="form-section">
      <!-- 头像上传 -->
      <view class="avatar-section">
        <image :src="formData.avatar_url || '/static/default-avatar.png'" class="avatar" mode="aspectFill"
          @click="chooseAvatar" />
        <text class="avatar-tip">{{ t('profile.editPage.avatar.tip') }}</text>
      </view>


      <view class="form-item">
        <text class="label">{{ t('profile.editPage.form.nickname') }}</text>
        <input v-model="formData.nickname" class="input" :placeholder="t('profile.editPage.form.nicknamePlaceholder')" />
      </view>

      <view class="form-item">
        <text class="label">{{ t('profile.editPage.form.email') }}</text>
        <input v-model="formData.email" class="input" :placeholder="t('profile.editPage.form.emailPlaceholder')" type="email" />
      </view>

      <view class="form-item">
        <text class="label">{{ t('profile.editPage.form.phone') }}</text>
        <input v-model="formData.phone" class="input" :placeholder="t('profile.editPage.form.phonePlaceholder')" type="number" />
      </view>


    </view>

    <!-- 保存按钮 -->
    <view class="button-section">
      <tui-button :disabled="loading" class="save-btn" shape="circle" type="submit" @click="saveProfile">
        {{ loading ? t('profile.editPage.save.saving') : t('profile.editPage.save.button') }}
      </tui-button>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <text>{{ t('profile.editPage.save.loadingText') }}</text>
    </view>
  </view>
</template>

<style scoped>
.container {
  min-height: 100vh;
  background: #f8f9fa;
}


.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.avatar-section {
  text-align: center;
  margin-bottom: 50rpx;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.avatar {
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  border: 4rpx solid #f0f0f0;
  transition: all 0.3s ease;
}

.avatar-tip {
  font-size: 24rpx;
  color: #666;
  margin-top: 20rpx;
  display: block;
}

.form-item {
  margin-bottom: 30rpx;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
  font-weight: 500;
}

.input {
  width: 100%;
  padding: 24rpx;
  border: 2rpx solid #e9ecef;
  border-radius: 12rpx;
  font-size: 28rpx;
  background: white;
  transition: all 0.3s ease;
  box-sizing: border-box;
  height: 88rpx;
  display: flex;
  align-items: center;
}

.input:focus {
  border-color: #007aff;
  box-shadow: 0 0 0 4rpx rgba(0, 122, 255, 0.1);
}



.button-section {
  margin: 20rpx;
  padding: 40rpx 0;
}


.save-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.3);
}


.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 28rpx;
}
</style>